/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.base.service.impl;

import com.dian.common.utils.DateUtils;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.common.utils.BeanConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import cn.hutool.core.util.StrUtil;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.dian.common.utils.PageUtils;
import com.dian.common.utils.Query;
import com.dian.common.server.CommonService;
import com.dian.modules.base.dao.SupplierDao;
import com.dian.modules.base.entity.SupplierEntity;
import com.dian.modules.base.service.SupplierService;
import com.dian.modules.base.vo.SupplierExportVO;

/**
 * 供应商服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-22 16:07:23
 */
@Service("supplierService")
public class SupplierServiceImpl extends ServiceImpl<SupplierDao, SupplierEntity> implements SupplierService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;


    /**
     * 供应商分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<SupplierEntity> page = this.page(new Query<SupplierEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
     *  供应商新增
     * @param supplierEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(SupplierEntity supplierEntity) {

        //设置编码，等基础默然初始化数据设置
        supplierEntity.setSupplierCode(commonService.getCode(SupplierEntity.class));
        //数据完整性校验
        this.paramsCheck(supplierEntity,AddGroup.class);

        //保存
        this.save(supplierEntity);

        return true;
    }

    /**
     *供应商更新
     * @param supplierEntity
     * @return
     */
    @Override
    public boolean updateInfo(SupplierEntity supplierEntity) {

        //修改状态校验
        this.updateCheck(supplierEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(supplierEntity, UpdateGroup.class);

        //更新主表
        this.updateById(supplierEntity);


        return true;
    }

    /**
     *供应商删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteInfo(Long[] ids) {

        //删除状态校验
        this.deleteCheck(ids);

        //更新主表
        this.remove(new QueryWrapper<SupplierEntity>().in("id",ids));

        return true;
    }

    /**
     * 供应商详情
     * @param id
     * @return
     */
    @Override
    public SupplierEntity getInfo(Long id) {
        SupplierEntity supplierEntity =getById(id);
        return supplierEntity;
    }

    /**
     * 供应商审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        SupplierEntity supplierEntity =this.getById(id);
        checkCheck(supplierEntity);
        //supplierEntity.setOrderState(OrderHead_OrderStateEnum.AUDITED.getValue());
        //supplierEntity.setOrderDate(new Date());
        ///supplierEntity.setCheckUserId(commonService.getUserId());
        //supplierEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(supplierEntity);
    }

    /**
     *供应商当前页or全部导出
     * @param params
     * @return
     */
    @Override
    public List<SupplierExportVO> exportList(Map<String, Object> params) {
        List<SupplierEntity> list;
        if(!StrUtil.isBlankIfStr(params.get("exprotType"))){
            list= this.page(new Query<SupplierEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }

        List<SupplierExportVO> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            resultList = BeanConverter.convertList(list, SupplierExportVO.class);
        }
        return resultList;
    }



    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        SupplierEntity supplierEntity =this.getById(id);
        //if(supplierEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
        //    throw new RRException(String.format("已审核的销售订单禁止修改"));
        //}
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(SupplierEntity supplierEntity) {
        //if(supplierEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
        //    throw new RRException(String.format("[%s] 此销售单已审核"));
        //}
    }

    /**
     * 删除状态校验
     *
     * @param ids
     */
    private void deleteCheck(Long[] ids) {
        for (Long id:ids) {
                SupplierEntity supplierEntity = this.getById(id);
        }
        //if(!saleOrderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.WAITCHECK.getValue())){
        //    throw new RRException(String.format("只允许删除未审核的销售订单"));
        //}
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(SupplierEntity record, Class<?> cls) {
        ValidatorUtils.validateEntity(record, cls);
    }
    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<SupplierEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<SupplierEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("supplierCode"))){
            queryWrapper.like("supplier_code",params.get("supplierCode"));
        }
        if(!StrUtil.isBlankIfStr(params.get("supplierName"))){
            queryWrapper.like("supplier_name",params.get("supplierName"));
        }
        if(!StrUtil.isEmptyIfStr(params.get("propKey"))){
            queryWrapper.and(wrapper -> wrapper
                   .like("supplier_code", params.get("propKey"))
                   .or()
                   .like("supplier_name", params.get("propKey"))
            );
        }

        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
